<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <page-filter
      v-model:query="filterInfo.query"
      :filter-list="filterInfo.list"
    >
      <template v-slot:filter-uploadFile>
        <el-upload
          :headers="uploadInfo.headers"
          :show-file-list="false"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
          :action="uploadInfo.action"
        >
          <el-button>导入模板</el-button>
        </el-upload>
      </template>
    </page-filter>
    <!-- 表格 -->
    <table-container
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="getUnitPage"
      :tab-index="true"
      :check-box="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle"
      @handleEvent="handleEvent"
    ></table-container>
    <!-- 新增修改弹窗 -->
    <page-dialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title[dialogInfo.type]"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- form -->
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
      />
    </page-dialog>
  </div>
</template>

<script setup name="unitManage">
import PageFilter from '@/components/PageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import { getUnitPage, createUnit, updateUnit } from '@/api/core.js'
import PageForm from '@/components/PageForm/index'
import PageDialog from '@/components/PageDialog/index'
import { ElLoading, ElMessage } from 'element-plus'
import { exportTemplateExcel } from '@/api/pub'
import axios from 'axios'

const { proxy } = getCurrentInstance()
// const getUnitPage = getUnitPage;
const uploadInfo = reactive({
  action: axios.defaults.baseURL + '/core/units/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    nameLike: '',
    sort: 'create_time desc',
    searchType: 'unit',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('unit:add'),
      event: create,
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
    },
    {
      type: 'slot',
      value: 'uploadFile',
    },
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '名称', value: 'name' },
    { label: '编码', value: 'code' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('unit:update'),
      },
    ],
  },
})
// 表单相关
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    { label: '名称', value: 'name', type: 'input', required: true },
    { label: '编码', value: 'code', type: 'input', required: true },
  ],
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    code: [
      { required: true, message: '请输入编码', trigger: 'blur' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
  },
  labelWidth: '100px',
})
// 弹窗相关
const dialogInfo = reactive({
  title: {
    create: '添加',
    update: '修改',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})

// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 初始化验证
function initRules() {
  formInfo.rules = proxy.$initRules(formInfo.fieldList)
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 创建
function create() {
  formInfo.data = {}
  dialogInfo.type = 'create'
  dialogInfo.visible = true
}
// 编辑
function update(data) {
  dialogInfo.type = 'update'
  dialogInfo.visible = true
  // 显示信息
  formInfo.data = { ...data }
}
function close() {
  dialogInfo.visible = false
  formInfo.data = {}
}
// 触发事件
function handleEvent(event, data) {
  switch (
    event
    // 对表格获取到的数据做处理
  ) {
  }
}
function save() {
  formInfo.ref.validate((valid) => {
    if (valid) {
      let api
      const params = formInfo.data
      const type = dialogInfo.type
      if (type === 'create') {
        api = createUnit
      } else if (type === 'update') {
        api = updateUnit
      } else {
        return
      }
      dialogInfo.btLoading = true
      proxy
        .$handleAPI(type, api, params)
        .then((res) => {
          if (res.success) {
            dialogInfo.visible = false
            tableInfo.refresh = Math.random()
          }
          dialogInfo.btLoading = false
        })
        .catch((e) => {
          dialogInfo.btLoading = false
        })
    }
  })
}
function beforeUpload(file) {
  
  //发生请求时打开加载动画
  uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some((type) => {
    console.log(file.name.split('.')[file.name.split('.').length - 1] === type)
    return file.name.split('.')[file.name.split('.').length - 1] === type
  })
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.loading.close()
    return false
  }
  return isFileType && isLt
}
function uploadSuccess(resp) {
  console.log(resp)
  uploadInfo.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.loading.close()
}
function downloadTemplate() {
  exportTemplateExcel('unit_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
</script>

<style scoped></style>
